import { Injectable,EventEmitter } from '@angular/core';
import { Http,URLSearchParams } from "@angular/http";
import { Observable } from "rxjs";
import "rxjs/Rx";  //这个是引用map方法引的。

@Injectable()
export class ProductService {

  //承担搜素模块和product列表的中间人
  searchEvent: EventEmitter<ProductSearchParams> = new EventEmitter;

  getAllCategories(): string[] {
    return ["电子产品","数码产品","大众喜爱","我的最爱"];
  }

  constructor(private http:Http) { }


  //第一个方法，获取所有的商品
  getProducts(): Observable<Product[]> {
    return this.http.get("/api/products").map(res => res.json());
  }
  //第二个方法：根据商品的id，找商品。
  getProduct(id: number): Observable<Product> {
    return this.http.get("/api/products/"+id).map(res => res.json());
  }
  //第三个方法：获取商品评论。
  getCommetsForProductId(id: number): Observable<Comment[]> {
    return this.http.get("/api/products/"+id+"/comments").map(res => res.json());
  }

  //实现搜索模块的
  search(params: ProductSearchParams): Observable<Product[]> {
    return this.http.get("/api/products", {search: this.encodeParams(params)}).map(res => res.json());
  }

  private encodeParams(params: ProductSearchParams) {
    let result: URLSearchParams;

    result = Object.keys(params)
    .filter(key => params[key])
    .reduce((sum:URLSearchParams, key:string) => {
      sum.append(key, params[key]);
      return sum;
    }, new URLSearchParams());

    return result;
  }

}

export class ProductSearchParams {
  constructor(public title:string,
              public price:number,
              public category:string
  ) {

  }
}

export class Product {
    constructor (
        public id:number,
        public title:string,
        public price:number,
        public rating:number,
        public desc:string,
        public categories:Array<string>
    ){

    }
}

//声明评论的类
export class Comment {
    constructor(
        public id: number,
        public productId: number,
        public timestamp: string,
        public user: string,
        public rating: number,
        public content: string) {

    }
}